<template>
  <a-config-provider :locale="locale">
    <div class="device—box">
      <!-- 条件搜索框 -->
      <div class="device—box-top">
        <div>
          <a-select placeholder="校区名称" style="width: 200px" showSearch  optionFilterProp="children" allowClear @change="handleChange">
            <a-select-option v-for="item in campus" :key="item.campusId" :value="item.campusId">
              {{ item.campusName }}
            </a-select-option>
          </a-select>
          <a-button type="primary" style="margin-left:10px;" @click="searchFn">查询</a-button>
        </div>
        <a-button icon="plus" @click="addDeviceFn">新增设备信息</a-button>
      </div>
      <!-- 表格 -->
      <div class="device—box-center">
        <a-table 
          :columns="columns" 
          :data-source="data" 
          :pagination="false" 
          :rowKey="record => record.campusId"
          :loading="tableLoading" 
          >
            <span slot="num" slot-scope="text, record, index">
              {{ (pageNum-1) * pageSize + parseInt(index) + 1 }}
            </span>
            <span slot="action" slot-scope="text, record, index">
              <a @click="toDetail(record, index)">查看</a>
            </span>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <a-pagination
          v-model="pageNum" 
          :total="total" 
          show-less-items 
          show-size-changer 
          show-quick-jumper
          :showTotal="showTotal"
          @change="changePage"
          @showSizeChange="changePageSize"
          />
      </div>
      <!-- 新增设备信息 -->
      <a-modal
        title="新增设备信息"
        :visible="visible"
        :footer="false"
        @cancel="visible = false"
      >
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
          <a-form-item label="校区名称">
            <a-select v-decorator="['campus', { rules: [{ required: true, message: '请选择校区' }]}]" placeholder="校区名称" style="width: 236px" showSearch  optionFilterProp="children" allowClear>
              <a-select-option v-for="item in campus" :key="item.campusId" :value="item.campusId">
                {{ item.campusName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="设备台数">
            <a-input v-decorator="['num', { rules: [{ required: true, message: '至少添加一台设备' }]}]" disabled></a-input>
          </a-form-item>
          <a-form-item
            v-for="(k, index) in form.getFieldValue('keys')"
            :key="k"
            v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
            :label="index === 0 ? '设备唯一码' : ''"
            :required="false"
          >
            <a-input
              v-decorator="[
                `names[${k}]`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: true,
                      whitespace: true,
                      message: '请输入设备唯一码',
                    },
                  ],
                },
              ]"
              placeholder="设备唯一码"
              style="width: 236px;"
            />
            <a-icon
              style="font-size:18px;"
              v-if="form.getFieldValue('keys').length > 1"
              type="delete"
              :disabled="form.getFieldValue('keys').length === 1"
              @click="() => remove(k)"
            />
          </a-form-item>
          <a-form-item v-bind="formItemLayoutWithOutLabel">
            <a-button type="dashed" style="width: 30%" @click="add">
              <a-icon type="plus" /> 添加
            </a-button>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
            <a-button @click="visible = false">取消</a-button>
            <a-button style="margin-left:10px;" type="primary" html-type="submit" :loading="loading">确定</a-button>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-config-provider>
</template>
<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN';
let id = 0;
const columns = [
  {
    title: '序号',
    dataIndex: 'num',
    key: 'num',
    width: 100, 
    align: 'center',
    scopedSlots: { customRender: 'num' }
  },
  {
    title: '校区名称',
    dataIndex: 'campusName',
    key: 'campusName',
    align: 'center',
    scopedSlots: { customRender: 'campusName' }
  },
  {
    title: '设备台数',
    dataIndex: 'total',
    key: 'total',
    align: 'center',
    scopedSlots: { customRender: 'total' }
  },
  {
    title: '启用数',
    key: 'onLine',
    dataIndex: 'onLine',
    align: 'center',
    scopedSlots: { customRender: 'onLine' },
  },
  {
    title: '停用数',
    key: 'offLine',
    dataIndex: 'offLine',
    align: 'center',
    scopedSlots: { customRender: 'offLine' },
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
];
export default {
  data() {
    return {
      locale: zhCN,
      campus:[], // 校区数据
      campusID:'', // 校区id
      data:[], // table数据 
      columns,
      pageNum:1, // 当前页
      pageSize:10, // 当前页展示条数
      total:null,
      visible:false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 19, offset: 5 },
        },
      },
      loading: false,
      tableLoading:false
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "add_device" });
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
  },
  created(){
    // 获取校区数据
    this.$axios('/rc/api/organization/campus').then(res => {
      if(res.success){
        this.campus = res.data
      }
    })
    this.getDataList() // 调用
  },
  methods:{
    // 更改校区选择
    handleChange(val){
      this.campusID = val ? val : ''
    },
    // 展示当前总条数
    showTotal(total, range){
      return `当前显示${range[0]}-${range[1]}条，共有 ${total}条`
    },
    // 改变分页
    changePage(page, pageSize){
      this.pageNum = page
      this.pageSize = pageSize
      this.getDataList()
    },
    // 改变条数
    changePageSize(current, size){
      this.pageNum = current
      this.pageSize = size
      this.getDataList()
    },
    // 查询
    searchFn(){
      this.getDataList()
    },
    // 获取列表
    getDataList(){
      this.tableLoading = true
      this.$axios(`/rc/api/device/page/list?pageNum=${this.pageNum}&pageSize=${this.pageSize}&campusId=${this.campusID}`).then(res => {
        if(res.success){
          this.data = res.data.records // 数据
          this.total = res.data.total // 总条数
          this.tableLoading = false
        }
      })
    },
    // 跳转详情（查看）
    toDetail(record, index){
      this.$router.push({ path: `/device/${record.campusId}`})
    },
    // 新增设备
    addDeviceFn(){
      this.form.resetFields();
      this.visible = true
    },
    // 删除
    remove(k) {
      const { form } = this;
      const keys = form.getFieldValue('keys');
      if (keys.length === 1) {
        return;
      }
      form.setFieldsValue({
        keys: keys.filter(key => key !== k),
        num: keys.filter(key => key !== k).length,
      });
    },
    // 添加
    add() {
      const { form } = this;
      const keys = form.getFieldValue('keys');
      const num = form.getFieldValue('num')
      const nextKeys = keys.concat(id++);
      form.setFieldsValue({
        keys: nextKeys,
        num: nextKeys.length
      });
    },
    // 点击确定（提交新增）
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          const arr = values.names.filter((s) => {
              return s && s.trim(); // 注：IE9(不包含IE9)以下的版本没有trim()方法
          });
          this.loading = true // 按钮loading加载
          this.$axios.post(`/rc/api/device/save`,{
            campusId:values.campus,
            deviceNames:arr
          }).then(res => {
            this.loading = false // 关闭按钮loading
            if(res.success){
              this.$message.success(res.message)
              this.visible = false 
              this.getDataList()
            }
          })
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
  .device—box{
    width:100%;
    height: 100%;
    .device—box-top{
      display: flex;
      justify-content: space-between;
    }
    .device—box-center{
      padding-top: 10px;
    }
    .pagination{
      display: flex;
      justify-content: flex-end;
      padding-top: 10px;
    }
  }
</style>